package jrmob.yonyou.com.commonlib.app_config_tool.tool.base;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import android.text.InputFilter;
import android.text.Spanned;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;

/**
 * 字符串操作工具包
 */
public class StringUtils {
	private static GregorianCalendar calendar = new GregorianCalendar();
	private final static Pattern emailer = Pattern
			.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
	private final static SimpleDateFormat dateFormater = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");
	private final static SimpleDateFormat dateFormater2 = new SimpleDateFormat(
			"yyyy-MM-dd");

	/**
	 * 将字符串转位日期类型
	 * 
	 * @param sdate
	 * @return
	 */
	public static Date toDate(String sdate) {
		try {
			return dateFormater2.parse(sdate);
		} catch (ParseException e) {
			return null;
		}
	}

	/**
	 * 将url地址中"：//"等转换"%"
	 * 
	 * @param url
	 * @return
	 */
	public static String urlToString(String url) {
		try {
			return URLEncoder.encode(url, "utf8");
		} catch (UnsupportedEncodingException e) {
			return "";
		}
	}

	/**
	 * 以友好的方式显示时间
	 * 
	 * @param sdate
	 * @return
	 */
	public static String friendly_time(String sdate) {
		Date time = toDate(sdate);
		if (time == null) {
			return "Unknown";
		}
		String ftime = "";
		Calendar cal = Calendar.getInstance();

		// 判断是否是同一天
		String curDate = dateFormater2.format(cal.getTime());
		String paramDate = dateFormater2.format(time);
		if (curDate.equals(paramDate)) {
			int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
			if (hour == 0)
				ftime = Math.max(
						(cal.getTimeInMillis() - time.getTime()) / 60000, 1)
						+ "分钟前";
			else
				ftime = hour + "小时前";
			return ftime;
		}

		long lt = time.getTime() / 86400000;
		long ct = cal.getTimeInMillis() / 86400000;
		int days = (int) (ct - lt);
		if (days == 0) {
			int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
			if (hour == 0)
				ftime = Math.max(
						(cal.getTimeInMillis() - time.getTime()) / 60000, 1)
						+ "分钟前";
			else
				ftime = hour + "小时前";
		} else if (days == 1) {
			ftime = "昨天";
		} else if (days == 2) {
			ftime = "前天";
		} else if (days > 2 && days <= 10) {
			ftime = days + "天前";
		} else if (days > 10) {
			ftime = dateFormater2.format(time);
		}
		return ftime;
	}

	/**
	 * 判断给定字符串时间是否为今日
	 * 
	 * @param sdate
	 * @return boolean
	 */
	public static boolean isToday(String sdate) {
		boolean b = false;
		Date time = toDate(sdate);
		Date today = new Date();
		if (time != null) {
			String nowDate = dateFormater2.format(today);
			String timeDate = dateFormater2.format(time);
			if (nowDate.equals(timeDate)) {
				b = true;
			}
		}
		return b;
	}

	/**
	 * 判断给定字符串是否空白串。 空白串是指由空格、制表符、回车符、换行符组成的字符串 若输入字符串为null或空字符串，返回true
	 * 
	 * @param input
	 * @return boolean
	 */
	public static boolean isEmpty(String input) {
		if (input == null || "".equals(input))
			return true;

		for (int i = 0; i < input.length(); i++) {
			char c = input.charAt(i);
			if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
				return false;
			}
		}
		return true;
	}

	/**
	 * 判断是不是一个合法的电子邮件地址
	 * 
	 * @param email
	 * @return
	 */
	public static boolean isEmail(String email) {
		if (email == null || email.trim().length() == 0)
			return false;
		return emailer.matcher(email).matches();
	}

	/**
	 * 字符串转整数
	 * 
	 * @param str
	 * @param defValue
	 * @return
	 */
	public static int toInt(String str, int defValue) {
		try {
			return Integer.parseInt(str);
		} catch (Exception e) {
		}
		return defValue;
	}

	/**
	 * 对象转整数
	 * 
	 * @param obj
	 * @return 转换异常返回 0
	 */
	public static int toInt(Object obj) {
		if (obj == null)
			return 0;
		return toInt(obj.toString(), 0);
	}

	/**
	 * 对象转整数
	 * 
	 * @param obj
	 * @return 转换异常返回 0
	 */
	public static long toLong(String obj) {
		try {
			return Long.parseLong(obj);
		} catch (Exception e) {
		}
		return 0;
	}

	/**
	 * 字符串转布尔值
	 * 
	 * @param b
	 * @return 转换异常返回 false
	 */
	public static boolean toBool(String b) {
		try {
			return Boolean.parseBoolean(b);
		} catch (Exception e) {
		}
		return false;
	}

	/**
	 * 获取当前时间字符串"yyyy-MM-d HH:mm:ss"
	 * 
	 * @return
	 */
	public static String getDateString() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-d HH:mm:ss");
		String dateString = formatter.format(currentTime);
		return dateString;
	}

	/**
	 * 根据输入的毫秒数，获得日期
	 * 
	 * @param millis
	 * @return
	 */
	public static int getDay(long millis) {
		calendar.setTimeInMillis(millis);
		return calendar.get(Calendar.DATE);
	}

	/**
	 * 获得当前时间的毫秒表示
	 * 
	 * @return
	 */
	public static long getNow() {
		GregorianCalendar now = new GregorianCalendar();
		return now.getTimeInMillis();

	}

	/**
	 *  根据输入的毫秒数，获得日期字符串
	 * @param millis
	 * @return
	 */
	public static String getDate(long millis) {
		calendar.setTimeInMillis(millis);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(calendar.getTime());
	}
	
	/**
	 * 获取今天
	 * @return
	 */
	public static String getToday(){
		return getDate(getNow());
	}

	/**
	 * 获取后天日期
	 * 
	 * @return
	 */
	public static String getTheDayData() {
		return getDate(getNow() + 86400000 + 86400000);
	}
	
	/**
	 * 获取前天日期
	 * 
	 * @return
	 */
	public static String getTheBeforeYesterday() {
		return getDate(getNow() - 86400000 - 86400000);
	}

	/**
	 * 当前时间字符串做文件名
	 * 
	 * @return
	 */
	public static String getFileName() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		String dateString = formatter.format(currentTime);
		return dateString;
	}

	/**
	 * 判断是否为合法IP
	 * 
	 * @return the ip
	 */
	public static boolean isboolIp(String ipAddress) {
		String ip = "\\b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\b";
		Pattern pattern = Pattern.compile(ip);
		Matcher matcher = pattern.matcher(ipAddress);
		return matcher.matches();
	}

	/**
	 * 获取指定长度的随机字符串
	 */
	public static String randomString(int len) {
		Random randGen = new Random();

		char[] letters = ("0123456789abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")
				.toCharArray();

		if (len < 1) {
			return null;
		}

		char[] buf = new char[len];
		for (int i = 0; i < len; i++) {
			buf[i] = letters[randGen.nextInt(71)];
		}
		return new String(buf);
	}

	/**
	 * GZIP解压
	 * 
	 * @param paramArrayOfByte
	 * @return
	 * @throws IOException
	 */
	public static String uncompress(byte[] paramArrayOfByte) throws IOException {
		ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
		GZIPInputStream localGZIPInputStream = new GZIPInputStream(
				new ByteArrayInputStream(paramArrayOfByte));
		byte[] arrayOfByte = new byte[256];
		int length = 0;

		while ((length = localGZIPInputStream.read(arrayOfByte)) != -1) {
			localByteArrayOutputStream.write(arrayOfByte, 0, length);
		}
		return localByteArrayOutputStream.toString();
	}

//	/**
//	 * 获取lasttime
//	 *
//	 * @param context
//	 * @param key
//	 * @return
//	 */
//	public static String getLasttime(Context context, String key) {
//		String lasttime = StringUtils.getPrefereceFileKeyValue(context, key);
//		if ("".equals(lasttime) || lasttime == null) {
//			lasttime = "2008-12-05 12:45:08";
//		}
//		return lasttime;
//	}

//	/**
//	 * 本地存值
//	 *
//	 * @param context
//	 * @param key
//	 * @param value
//	 */
//	public static void createPrefereceFile(Context context, String key,
//			String value) {
//		SharedPreferences prefs = PreferenceManager
//				.getDefaultSharedPreferences(context);
//		Editor edit = prefs.edit();
//		edit.putString(key, value);
//		edit.commit();
//	}

	/**
	 * 清空本地值
	 * 
	 * @param context
	 * @param key
	 */
	public static void clearPrefereceFile(Context context, String key) {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(context);
		Editor edit = prefs.edit();
		edit.remove(key);
		edit.commit();
	}

//	/**
//	 * 本地取值
//	 *
//	 * @param context
//	 * @param key
//	 * @return
//	 */
//	public static String getPrefereceFileKeyValue(Context context, String key) {
//		SharedPreferences prefs = PreferenceManager
//				.getDefaultSharedPreferences(context);
//		String value = prefs.getString(key, "");
//		return value;
//	}

	/**
	 * 输入框过滤器 过滤表情符 TODO
	 * 
	 * @return
	 */
	public static InputFilter[] getInputFilter() {
		InputFilter[] emojiFilter = new InputFilter[] { new InputFilter() {
			Pattern emoji = Pattern
					.compile(
							"[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
							Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);

			public CharSequence filter(CharSequence src, int start, int end,
					Spanned dst, int dstart, int dend) {
				Matcher emojiMatcher = emoji.matcher(src);
				if (emojiMatcher.find()) {
					return "";
				}
				return null;
			}
		}, new InputFilter.LengthFilter(20) };
		return emojiFilter;
	}

	/**
	 * 解析个人详细信息Hml标签
	 * 
	 * author chensong
	 * 
	 * @param htmlStr
	 * @return
	 */
	public static HashMap<String, String> getHtmlContent(String htmlStr) {
		HashMap<String, String> mMap = new HashMap<String, String>();
		String[] classifyID = { "userTitle", "userPost", "companyTel",
				"Iphone", "homeNumber", "fax" };
		String regEx_html[] = { "<Title>([^</Title>]*)", "<Rank>([^</Rank>]*)",
				"<CompanyPhone>([^</CompanyPhone>]*)",
				"<mobile>([^</mobile>]*)", "<HomePhone>([^</HomePhone>]*)",
				"<faxnum>([^</faxnum>]*)" };// 定义HTML标签的正则表达式

		for (int i = 0; i < regEx_html.length; i++) {
			Pattern p = Pattern.compile(regEx_html[i]);// 匹配<title>开头，</title>结尾的文档
			Matcher m = p.matcher(htmlStr);// 开始编译
			// html = m.replaceAll(";"); // 过滤html标签
			while (m.find()) {
				System.out.println("getContext------------>" + m.group(1) + ";"
						+ classifyID[i]);
				mMap.put(classifyID[i], m.group(1));// 获取被匹配的部分
			}
		}
		return mMap;
	}
}